package com.hengtian.roastwall.controller;

import com.hengtian.roastwall.app.MyApp;
import com.hengtian.roastwall.entity.User;
import com.hengtian.roastwall.listener.myEvent.TestApplicationEvent;
import com.hengtian.roastwall.service.UserService;
import com.hengtian.roastwall.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping
@Slf4j
public class TestController {

    @Autowired
    private UserService userService;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    MyApp myApp;

    @GetMapping("/getTest")
    // 设置访问权限, 有其中任意一个就可以访问
    @PreAuthorize("hasAnyAuthority('system:dept:list', 'aaa')")
//    @PreAuthorize("hasAuthority('system:dept:list')")     // 需要有system:dept:list权限才能访问
    public String testGet() {
        myApp.init();
        myApp.shutdown();
        return "getTest";
    }

    @GetMapping("/getTest1")
    // 添加自定义的权限校验
//    @PreAuthorize("@ex.hasAuthority('system:dept:list')")
    public String testGet1() {
        myApp.init();
        myApp.shutdown();
        return "getTest1";
    }

    @GetMapping("/getTest2")
    public String testGet2() {
        myApp.init();
        myApp.shutdown();
        return "getTest2";
    }

    @GetMapping("/getAllUsers")
    @Transactional(rollbackFor = Exception.class)
    public List<User> getAllUsers() {
        try {
            userService.addUser(new User(3l, "test", "test", "123456"));
        } catch (Exception e) {
            e.printStackTrace();
        }
//        userService.addUser(new User(3l, "test", "test", "123456"));
        List<User> users = userService.getAllUsers();
//        throw new RuntimeException("我抛");

        return users;
    }

    @PostMapping
    public ResponseResult addUser(@RequestBody User user) {
        userService.addUser(user);
//        throw new RuntimeException("插入失败");
        return new ResponseResult(200, "添加用户成功");
    }

    @GetMapping("/testEvent")
    public ResponseResult testEvent(){
        eventPublisher.publishEvent(new TestApplicationEvent(this,"监听器测试"));

        return new ResponseResult(200, "监听器测试");
    }
}
